define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue', 'cookie'], function ($, undefined, Backend, Table, Form, Vue) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'customer.intention/index' + location.search,
                    add_url: 'customer.intention/add',
                    edit_url: 'customer.intention/edit',
                    del_url: 'customer.intention/del',
                    multi_url: 'customer.intention/multi',
                    import_url: 'customer.intention/import',
                    table: 'customer',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                queryParams: (params) => {
                    var filter = JSON.parse(params.filter)
                    var op = JSON.parse(params.op)

                    filter.customer_type = 0
                    op.customer_type = '='

                    params.filter = JSON.stringify(filter)
                    params.op = JSON.stringify(op)

                    return params
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'customer_identity',
                            title: '业务类型',
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.status,
                            custom: {1: "green"},
                            searchList: {0: '个人', 1: '公司'}
                        },
                        {
                            field: 'full_name',
                            title: '客户姓名',
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'idnumber',
                            title: '身份证号',
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'corporate_name',
                            title: '公司名称',
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        }, {
                        field: 'signatory',
                        title: '授权签约人',
                        operate: 'LIKE',
                        table: table,
                        class: 'autocontent',
                        formatter: Table.api.formatter.content
                    },
                        {field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
                        // {
                        //     field: 'status',
                        //     title: '审核状态',
                        //     formatter: Table.api.formatter.status,
                        //     custom: {1: "orange", 2: "aqua", 3: 'red'},
                        //     searchList: {0: '待提交', 1: '审核中', 2: '审核通过', 3: '审核不通过'}
                        // },
                        // {
                        //     field: 'ht_status',
                        //     title: '合同状态',
                        //     custom: {0: "red", 1: "green",},
                        //     searchList: {0: '未签名', 1: '客户已签名'},
                        //     formatter: Table.api.formatter.status,
                        // },
                        // {field: 'customer_type', title: __('Customer_type')},
                        {
                            field: 'corporate_type',
                            title: __('Corporate_type'),
                            formatter: Table.api.formatter.status,
                            custom: {1: "green", 2: "red"},
                            searchList: {0: '个体户', 1: '小规模纳税人', 2: '一般纳税人'}
                        },
                        {field: 'region', title: __('Region'), operate: 'LIKE'},
                        {
                            field: 'admin_info.nickname',
                            title: '销售名称',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'total_amount',
                            title: '总成交金额',
                            operate: false,
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'audit_status',
                            title: '审核信息',
                            operate: false,
                            formatter: function (value, row, index) {
                                var str = ''
                                str += '未提交：' + value.wtj + '<br/>'
                                str += '审核中：' + value.shz + '<br/>'
                                str += '审核通过：' + value.shtg + '<br/>'
                                str += '审核不通过：' + value.shbtg
                                return str
                            }
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                // {
                                //     name: 'deal',
                                //     text: __('标记为成交客户'),
                                //     title: __('标记为成交客户'),
                                //     url: 'customer/intention/deal',
                                //     classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                //     success: function (data, ret) {
                                //         table.bootstrapTable('refresh');
                                //     },
                                //     error: function (data, ret) {
                                //         Layer.alert(ret.msg);
                                //         return false;
                                //     }
                                // },
                                {
                                    name: 'addtabs',
                                    text: __('服务列表'),
                                    title: __('服务列表'),
                                    extend: 'data-area=\'["80%","80%"]\'',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: 'customer/package/index',
                                    visible: function (row) {
                                        if (Config['fuwuliebiao']) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },

                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
                onLoadSuccess: function () {
                    var cookiefilenames = 'customer_index_controller';  //对应控制器列表页
                    table.on('column-switch.bs.table', function (e, json) {
                        var hideColumns = [];
                        $.each(table.bootstrapTable('getHiddenColumns'), function (i, item) {
                            hideColumns.push(item.field);
                        });
                        $.cookie('texie_' + cookiefilenames, JSON.stringify(hideColumns), {expires: 365, path: '/'});
                    });
                    if ($.cookie('texie_' + cookiefilenames)) {
                        $.each(JSON.parse($.cookie('texie_' + cookiefilenames)), function (i, item) {
                            table.bootstrapTable('hideColumn', item);
                        });
                    }
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $('input[name="row[customer_identity]"]').change(() => {
                const value = $('input[name="row[customer_identity]"]:checked').val()
                if (value == 0) {
                    $('#identity').html(' <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">客户姓名:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-full_name" placeholder="' + __('Please enter') + '客户姓名" data-rule="required"\n' +
                        '                       class="form-control" name="row[full_name]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>\n' +
                        '        <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">身份证号:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-idnumber" placeholder="' + __('Please enter') + '身份证号" data-rule="required"\n' +
                        '                       class="form-control" name="row[idnumber]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>')
                } else {
                    $('#identity').html('<div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">公司名称:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-corporate_name" placeholder="' + __('Please enter') + '公司名称" data-rule="required" class="form-control"\n' +
                        '                       name="row[corporate_name]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>\n' +
                        '        <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">授权签约人:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-signatory" placeholder="' + __('Please enter') + '授权签约人" data-rule="required"\n' +
                        '                       class="form-control" name="row[signatory]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>')
                }
            })


            const service = Config['service'] || []
            const types = [
                'gth',
                'xgmnsr',
                'ybnsr',
            ]
            $('#c-service').change((e) => {
                rendService()
            })
            $('input[name="row[corporate_type]"]').change(() => {
                rendService()
            })

            function rendService() {
                const value = $('#c-service').val()
                const corporate_type = $('input[name="row[corporate_type]"]:checked').val()

                var index = 0
                const field_name = 'serviceTable'

                var str = '<table border="1" width="100%" style="margin-top: 10px">'
                str += "<tr>"
                str += '<td>服务名称</td>'
                str += '<td>标准价格</td>'
                str += '<td>成交价格</td>'
                str += '<td>服务周期（月）</td>'
                str += '<td>本次收款</td>'
                str += '<td>剩余尾款</td>'
                str += "</tr>"

                service.forEach(item => {
                    if (value.includes(item.id.toString())) {
                        str += "<tr>"
                        str += '<td>' + item.service_name + '</td>'
                        str += '<td>￥' + item[types[corporate_type] + '_standard_price'] + '</td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_deal_price" class="form-control deal_price_ks" value="' + item[types[corporate_type] + '_standard_price'] + '" name="row[' + field_name + '][' + index + '][deal_price]" placeholder="请输入成交价格" data-rule="required;" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_month" class="form-control" name="row[' + field_name + '][' + index + '][month]" placeholder="服务周期" data-rule="" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_collection_price" class="form-control collection_price_ks" name="row[' + field_name + '][' + index + '][collection_price]" placeholder="本次收款" data-rule="required" type="text"/></td>'
                        str += '<td><input index="' + index + '" bs="' + index + '_balance_price" class="form-control balance_price_ks" name="row[' + field_name + '][' + index + '][balance_price]" placeholder="剩余尾款" data-rule="required" type="text"/></td>'
                        str += "</tr>"
                        str += '<input name="row[' + field_name + '][' + index + '][service_id]" value="' + item.id + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][ledger_expenses]" value="' + item.ledger_expenses + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][service_name]" value="' + item.service_name + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][standard_price]" value="' + item[types[corporate_type] + '_standard_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][cost_price]" value="' + item[types[corporate_type] + '_cost_price'] + '" type="hidden"/>'
                        str += '<input name="row[' + field_name + '][' + index + '][corporate_type]" value="' + corporate_type + '" type="hidden"/>'
                        index++
                    }
                })
                str += "</table>"
                $('#select-privew').html(str)

                $('.deal_price_ks').change(function () {
                    var index = $(this).attr('index');
                    $('input[bs=' + index + '_collection_price]').val(null)
                    $('input[bs=' + index + '_balance_price]').val(null)
                })

                $('.collection_price_ks').change(function () {
                    var index = $(this).attr('index');
                    var val = $(this).val();
                    var deal_price = $('input[bs=' + index + '_deal_price]').val()
                    if (Number(val) > Number(deal_price)) {
                        $(this).val(deal_price)
                        val = deal_price
                    }
                    $('input[bs=' + index + '_balance_price]').val(deal_price - val)
                })
            }

            Controller.api.bindevent();
        },
        edit: function () {
            $('input[name="row[customer_identity]"]').change(() => {
                const value = $('input[name="row[customer_identity]"]:checked').val()
                if (value == 0) {
                    $('#identity').html(' <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">客户姓名:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-full_name" placeholder="' + __('Please enter') + '客户姓名" data-rule="required"\n' +
                        '                       class="form-control" name="row[full_name]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>\n' +
                        '        <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">身份证号:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-idnumber" placeholder="' + __('Please enter') + '身份证号" data-rule="required"\n' +
                        '                       class="form-control" name="row[idnumber]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>')
                } else {
                    $('#identity').html('<div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">公司名称:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-corporate_name" placeholder="' + __('Please enter') + '公司名称" data-rule="required" class="form-control"\n' +
                        '                       name="row[corporate_name]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>\n' +
                        '        <div class="form-group">\n' +
                        '            <label class="control-label col-xs-12 col-sm-2">授权签约人:</label>\n' +
                        '            <div class="col-xs-12 col-sm-8">\n' +
                        '                <input id="c-signatory" placeholder="' + __('Please enter') + '授权签约人" data-rule="required"\n' +
                        '                       class="form-control" name="row[signatory]" type="text">\n' +
                        '            </div>\n' +
                        '        </div>')
                }
            })

            Controller.api.bindevent();
        },

        deal: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
